package com.rr.middle;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * @author zhuangcanrun
 * @Date 2022/01/06/12:49
 * @description
 **/

public class SimplifyPath {
    public String simplifyPath(String path) {
        List<String> nodeList = new ArrayList<>();
        int length = path.length();
        StringBuilder sb = new StringBuilder();
        for (int i = 1; i < length; i++) {
            char c = path.charAt(i);
            if (c == '/' && sb.length() != 0) {
                nodeList.add(sb.toString());
                sb = new StringBuilder();
            } else if (c != '/') {
                sb.append(c);
                if (i == length - 1) {
                    nodeList.add(sb.toString());
                }
            }
        }
        Stack<String> stack = new Stack<>();
        for (String node : nodeList) {
            if (node.equals(".")) {
                continue;
            } else if (node.equals("..")) {
                if (stack.size() != 0) {
                    stack.pop();
                }
            } else {
                stack.add(node);
            }
        }
        sb = new StringBuilder("/");
        for (String s : stack) {
            sb.append(s).append("/");
        }
        if (sb.length() != 1) {
            sb.deleteCharAt(sb.length() - 1);
        }
        return sb.toString();
    }

    public static void main(String[] args) {
        SimplifyPath simplifyPath = new SimplifyPath();
        System.out.println(simplifyPath.simplifyPath("/a//b////c/d//././/.."));
    }
}
